<template>
  <div>
    <MyTable :arr="list">
      <template #header>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #body="scope">
        <td>{{ scope.row.id }}</td>
        <td>{{ scope.row.goods_name }}</td>
        <td>{{ scope.row.goods_price }}</td>
        <td>
            <!--给 input 框绑定v-if事件  
          inputVisible的值决定每个input的显示 
           v-aaa 自定义事件 让input 获得焦点
           @blur 失去焦点时 阴藏input
            v-model 双向绑定 inputValue"
            @keydown.esc 绑定键盘按下事件 esc 清空 value 值
            @keydown.enter 按下回车键 把input的value push给 row.tags

          -->
          <input
            class="tag-input form-control"
            style="width: 100px"
            type="text"
            v-if="scope.row.inputVisible"
            v-focus
            @blur="scope.row.inputVisible = false"
            v-model="scope.row.inputValue"
            @keydown.esc="scope.row.inputValue = ''"
            @keydown.enter="enterFn(scope.row)"
          />
          <button
            v-else
            style="display: block"
            class="btn btn-primary btn-sm add-tag"
            @click="scope.row.inputVisible = true"
          >
            +Tag
          </button>
          <!-- 遍历数组的标识 添加徽章 -->
          <span
            v-for="(item, index) in scope.row.tags"
            :key="index"
            class="badge bg-warning"
          >
            {{ item }}
          </span>
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="delFn(scope.row.id)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from "../components/MyTable.vue";
// 局部注册axios
import axios from "axios";
// 基础地址
axios.defaults.baseURL = "https://www.escook.cn";
export default {
  data() {
    return {
      list: [],
    };
  },
  components: {
    MyTable,
  },
  // 在created 生命周期 发起axios 请求
  created() {
    axios({
      url: "/api/goods",
    }).then((res) => {
      // 把请求回来的数据 赋值给list
      this.list = res.data.data;
    });
  },
  methods: {
    // 点击删除按钮 把对应的id 传过来 过滤到当前项
    delFn(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    enterFn(obj) {
      // console.log(obj.inputValue);
      // 判断inputValue 为空 
      if (obj.inputValue.trim().length === 0) {
        alert("请输入正确的数据");
        return;
      } 
      // 反之推给  obj.tags 数组  清空输入框
      obj.tags.push(obj.inputValue);
      obj.inputValue = "";
    },
  },
};
</script>
<style></style>
